/*获取订单号*/
var orderId = sessionStorage.getItem("id");
var typeId = sessionStorage.getItem("type");
var coupontype=""
var platform=""
var manjian=""
if (typeId==1){
    $("#changePrice").attr("disabled","disabled");
    $("#zhe").attr("disabled","disabled");
    $("#gai").attr("disabled","disabled");
    $("#freight").attr("disabled","disabled");
    $("#customServiceRemark").attr("disabled","disabled");
    $("#abiaoqian").hide()
    $("#PriceChangeTrue").val("返回");
}
var lvtotal=0
getOrderDetail();
/*通过订单号获取订单详情*/
function getOrderDetail(){
    $("#newdatatable").hide()
    $("#datatable").show()
    $.ajax({
        type: "POST",
        url: root.orderInter.order_queryOrderDetails,
        cache: false, //禁用缓存
        dataType: "json",
        data: {
            order_id: orderId, // 订单编号
        },
        success: function(result) {
            if(result.orderCoupon!=null){
                coupontype=result.orderCoupon.coupon_type
            }
            platform=result.orderExt.platform
            sessionStorage.setItem("orderDetail", JSON.stringify(result));
            renderOrderPage(result);

            //将所有按钮隐藏
            $("#affirmMoney").siblings().css({
                display: "none"
            });
            /*确认认款按钮判断*/
            if((result.orderBase.paid_type == 1301 || result.orderBase.paid_type == 1401) && result.orderBase.order_status == 10) {
                if(result.orderBase.customer_verify_status == 0){
                    /* $("#orderCheckStatus").css({
                         display: "inline"
                     });*/
                    $("#affirmMoney").css({
                        display: "none"
                    });
                }
                if(result.orderBase.customer_verify_status == 10){
                    $("#orderAnomalCheckStatus").css({
                        display: "none"
                    });
                    $("#affirmMoney").css({
                        display: "inline"
                    });
                }
            } else if(result.orderBase.paid_type == 1101 && result.orderBase.order_status == 70) {
                if(result.listOrderRemark.length == 0) {
                    $("#comfirmMoneyRemark").val("");
                    $("#affirmMoney").css({
                        display:"inline"
                    })
                } else {
                    for(var i=0;i<result.listOrderRemark.length;i++){
                        if(result.listOrderRemark[i].operate_type == 10){
                            $("#affirmMoney").css({
                                display:"none"
                            })
                            $("#comfirmMoneyRemark").html(result.listOrderRemark[i].remark);//确认认款备注
                        }else {
                            $("#comfirmMoneyRemark").val("");
                            $("#affirmMoney").css({
                                display: "inline"
                            });
                        }
                    }
                }
            }
            switch(result.orderBase.order_status) {
                case 9:
                    /*待审核*/

                    $("#detailCancel").css({
                        display: "inline"
                    });

                    break;
                case 10:
                    /*待付款*/

                    $("#detailCancel").css({
                        display: "inline"
                    });

                    break;
                /*订单状态*/
                case 20:
                    /*待审核*/
                    $("#detailCancel").css({
                        display: "inline"
                    });
                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $("#orderSureStatus").css({
                        display: "none"
                    });
                    break;
                case 30:
                    /*待配货*/

                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $(".updataBtn").css({
                        display: "inline"
                    });
                    $("#detailCancel").css({
                        display: "none"
                    });
                    /*$("#clientRejection").css({
                        display: "inline"
                    });*/
                    break;
                case 40:
                    /*待出库*/

                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $("#detailCancel").css({
                        display: "inline"
                    });
                    if(result.cancle_apply_show==false){
                        $("#quxiao").css({
                            display: "inline"
                        });
                        $("#detailCancel").css({
                            display: "none"
                        });
                    } else {
                        $("#quxiao").css({
                            display: "none"
                        });
                        $("#detailCancel").css({
                            display: "inline"
                        });

                    }
                    break;
                case 50:
                    /*待发货*/
                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $("#detailCancel").css({
                        display: "inline"
                    });
                    break;
                case 60:
                    /*待收货*/

                    $("#affirmMoney").css({
                        display: "none"
                    });


                    if(result.is_rejected != 1){
                        $("#clientRejection").css({
                            display: "inline"
                        });
                    }

                    break;
                case 70:
                    /*已收货，待结算*/
                    if (result.is_show==true){
                        $("#maintain").css({
                            display: "inline"
                        });
                        $("#returnGoods").css({
                            display: "inline"
                        });
                    }
                    $("#returnInfoBox").css({
                        display: "block"
                    });
                    break;
                case 80:
                    /*订单成功*/
                    $("#affirmMoney").css({
                        display: "none"
                    });


                    if (result.is_show==true){
                        $("#maintain").css({
                            display: "inline"
                        });
                        $("#returnGoods").css({
                            display: "inline"
                        });
                    }
                    $("#returnInfoBox").css({
                        display: "block"
                    });
                    break;
                case 90:
                    /*交易完成*/
                    $("#affirmMoney").css({
                        display: "none"
                    });
                    if (result.is_show==true){
                        $("#maintain").css({
                            display: "inline"
                        });
                        $("#returnGoods").css({
                            display: "inline"
                        })
                    }
                    $("#returnInfoBox").css({
                        display: "block"
                    });
                    break;
                case 100:
                    /*已取消*/
                    if(result.buy_again_button==true){
                        $("#buyAgain").css({
                            display: "inline"
                        });
                    }else {
                        $("#buyAgain").css({
                            display: "none"
                        });
                    }

                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $("#orderSureStatus").css({
                        display: "none"
                    });
                    $("#customerCheck").hide();
                    $("#customerServiceCheck").hide();
                    $("#cancleReason").css({
                        display: "inline"
                    });
                    if(result.orderCancle.cancel_role == 10) {
                        $("#cancleReason").html("客户主动取消");
                    } else if(result.orderCancle.cancel_role == 20) {
                        $("#cancleReason").html("客服取消");
                    } else if(result.orderCancle.cancel_role == 30) {
                        $("#cancleReason").html("超时未支付取消");
                    }
                    $(".cancleBox").css({
                        display: "inline"
                    });
                    $("#returnInfoBox").css({
                        display: "block"
                    });
                    break;
                case 110:
                    /*交易关闭*/

                    $("#returnReason").css({
                        display: "inline"
                    });
                    $("#affirmMoney").css({
                        display: "none"
                    });
                    $("#returnInfoBox").css({
                        display: "block"
                    });
                    $(".closeBox").css({
                        display: "block"
                    });
                    break;
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
/*转换状态函数*/
function changeOrderState(orderState) {
    switch(orderState) {
        /*订单状态*/
        case 9:
            return "待付款";
            break;
        case 10:
            return "待付款";
            break;
        case 20:
            return "待审核";
            break;
        case 30:
            return "待配货";
            break;
        case 40:
            return "待出库";
            break;
        case 50:
            return "待发货";
            break;
        case 60:
            return "待收货";
            break;
        case 70:
            return "已收货，待结算";
            break;
        case 80:
            return "已完成";
            break;
        case 90:
            return "交易完成";
            break;
        case 100:
            return "已取消";
            break;
        case 110:
            return "交易关闭";
            break;
    }
}
function calculate(listAddressReceiver,type) {
    var math=""
    var phone=""
    var size=listAddressReceiver.length
    if (listAddressReceiver.length==0){
        return "";
    }
    for (i=0;i<size;i++){
        if (i<size-1){
            math+=listAddressReceiver[i].receiver_name+" ; "
            phone+=listAddressReceiver[i].mobile+" ; "
        }else {
            math+=listAddressReceiver[i].receiver_name
            phone+=listAddressReceiver[i].mobile
        }
    }
    if (type==1){
        return math
    }else {
        return phone
    }
}

function changePayTypeState(payTypeState) {
    switch(payTypeState) {
        /*支付方式*/
        case 1001:
            return "在线支付";
            break;
        case 1002:
            return "支付宝支付";
            break;
        case 1003:
            return "微信支付";
            break;
        case 1101:
            return "货到付款";
            break;
        case 1102:
            return "货到付款-现金";
            break;
        case 1103:
            return "货到付款-pos机";
            break;
        case 1201:
            return "账期支付";
            break;
        case 1301:
            return "银行转账";
            break;
        case 1401:
            return "银行汇票";
            break;
    }
}


function changePayState(payTypeState) {
    switch(payTypeState) {
        /*支付方式*/
        case 1001:
            return "在线支付";
            break;
        case 1002:
            return "线上支付";
            break;
        case 1003:
            return "线上支付";
            break;
        case 1101:
            return "货到付款";
            break;
        case 1201:
            return "账期支付";
            break;
        case 1301:
            return "银行转账";
            break;
        case 1401:
            return "银行汇票";
            break;
    }
}

function changeDeliveryMethodType(DeliveryMethodType) {
    switch(DeliveryMethodType) {
        /*配送方式*/
        /*case 10:
            return "鑫方盛物流";
            break;
        case 20:
            return "店内自提";
            break;*/
        case 10:
            return "快递";
            break;
        case 20:
            return "快运-送货上门";
            break;
        case 30:
            return "快运-站点自提";
            break;
        case 40:
            return "鑫方盛物流";
            break;
        case 50:
            return "上门自提";
            break;
    }
}

function changeInvoiceType(invoiceType) {
    switch(invoiceType) {
        /*发票类型*/
        case 10:
            return "增值税";
            break;
        case 20:
            return "普税";
            break;
    }
}

function changeCancleReason(cancleReason) {
    switch(cancleReason) {
        /*取消原因*/
        case 10:
            return "订购错误";
            break;
        case 11:
            return "价格高";
            break;
        case 12:
            return "无法满足到货时效";
            break;
        case 13:
            return "支付问题";
            break;
        case 14:
            return "重复下单";
            break;
        case 15:
            return "暂时不需要";
            break;
        case 16:
            return "订单信息有误";
            break;
        case 17:
            return "无货";
            break;
        case 18:
            return "其他";
            break;
        case 110:
            return "公司产品原因";
            break;
        case 101:
            return "客户原因";
            break;
    }
}
function changeCloseReason(closeReason) {
    switch(closeReason) {
        /*关闭原因*/
        case 10:
            return "商品质量问题";
            break;
        case 20:
            return "大小/型号与商品描述不符";
            break;
        case 30:
            return "颜色/图案与商品描述不符";
            break;
        case 40:
            return "功能/效果与商品描述不符";
            break;
        case 50:
            return "商城发错货";
            break;
        case 60:
            return "少件/漏件";
            break;
        case 70:
            return "多买/买错不想要了";
            break;
        case 80:
            return "到货物流破损";
            break;
        case 90:
            return "发票问题";
            break;
        case 100:
            return "未按约定时间发货";
            break;
        case 110:
            return "其他原因";
            break;
    }
}

/*渲染页面*/
/*头部按钮*/

function affirmMoney() {
    //权限判断
    if(sessionStorage.getItem("regions")!=""){
        if(sessionStorage.getItem("regions").match(JSON.parse(sessionStorage.getItem("orderDetail")).orderBase.warehouse_id)){

            /*确认认款*/
            layer_show("确认收款", "../orderList/affirmMoneyAlert.html", "600", "300");


        }else {
            $.Huimodalalert('暂无此订单处理权限！', 2000);

        }
    }else {
        $.Huimodalalert('暂无此订单处理权限！', 2000);

    }


}
/*跳转拒收页面*/
function clientRejection(title, url) {
    //权限判断
    if(sessionStorage.getItem("regions")!=""){
        if(sessionStorage.getItem("regions").match(JSON.parse(sessionStorage.getItem("orderDetail")).orderBase.warehouse_id)){

            var index = layer.open({
                type: 2,
                title: title,
                content: url
            });
            layer.full(index);

        }else {
            $.Huimodalalert('暂无此订单处理权限！', 2000);

        }
    }else {
        $.Huimodalalert('暂无此订单处理权限！', 2000);

    }


}
var isIngReturn = false;
function returnGoods(title) {
    if(sessionStorage.getItem("regions")!=""){
        if(sessionStorage.getItem("regions").match(JSON.parse(sessionStorage.getItem("orderDetail")).orderBase.warehouse_id)){

            if(isIngReturn){
                // layer.msg('请求已提交，请勿重复点击！');
                return false;
            }
            isIngReturn = true;
            getOrderDetail();
            setTimeout(function () {
                var orderDetail = JSON.parse(sessionStorage.getItem("orderDetail"));
                var orderState = orderDetail.orderBase.order_status;
                if(orderState == "70") {
                    var url = "orderSuccess_refund.html";
                } else if(orderState == "80") {
                    var url = "orderSuccess_refund.html";
                }
                else if(orderState == "90") {
                    var url = "orderSuccess_refund.html";
                }
                var index = layer.open({
                    type: 2,
                    title: title,
                    content: url
                });
                layer.full(index);
            },200)
        }else {
            $.Huimodalalert('暂无此订单处理权限！', 2000);

        }
    }else {
        $.Huimodalalert('暂无此订单处理权限！', 2000);
    }



}
var isIngMaintain = false;

function customerRepair(title) {
    //权限判断
    if(sessionStorage.getItem("regions")!=""){
        if(sessionStorage.getItem("regions").match(JSON.parse(sessionStorage.getItem("orderDetail")).orderBase.warehouse_id)){
            if(isIngMaintain){
                // layer.msg('请求已提交，请勿重复点击！');
                return false;
            }
            isIngMaintain = true;
            getOrderDetail();
            setTimeout(function () {
                var orderDetail = JSON.parse(sessionStorage.getItem("orderDetail"));
                var orderState = orderDetail.orderBase.order_status;
                var url = "";
                if(orderState == "70") {
                    url = "orderSuccess_maintainGoods.html";
                } else if(orderState == "80") {
                    url = "orderSuccess_maintainGoods.html";
                } else if(orderState == "90") {
                    url = "orderSuccess_maintainGoods.html";
                }
                var index = layer.open({
                    type: 2,
                    title: title,
                    content: url
                });
                layer.full(index);
            },200);
        }else {
            $.Huimodalalert('暂无此订单处理权限！', 2000);

        }
    }else {
        $.Huimodalalert('暂无此订单处理权限！', 2000);

    }

}

function detailCancel() {
    //权限判断
    if(sessionStorage.getItem("regions")!=""){
        if(sessionStorage.getItem("regions").match(JSON.parse(sessionStorage.getItem("orderDetail")).orderBase.warehouse_id)){

            layer_show("取消订单", "../orderList/cancleAlert.html", "600", "300");


        }else {
            $.Huimodalalert('暂无此订单处理权限！', 2000);

        }
    }else {
        $.Huimodalalert('暂无此订单处理权限！', 2000);

    }

}

/*function buyAgain() {
    window.location.href = "../replaceOrder/replace-order-01.html";
}*/
//再次购买
/*$('#buyAgain').click(function () {
    sessionStorage.setItem("order_id",orderId);
    console.log($(window.parent.parent.document))
    $(window.parent.parent.document).find("#replaceOrder")[0].click();
});*/
/*datatable*/
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];
var length=0
var lengthSister=0
var youvalue=1
var newzhekou=0
var list=[]
// 满金额减
var fullAmountMapValue=0
// 满数量减
var fullQuantityValue=0
// 特价
var promotionValueTotal=0

function submitOrder() {
    if ($("#express_company").val()==''||$("#express_number").val()==''){
        layer.msg('请填写配送方式和配送订单号', {icon: 6, time: 1000});
        return;
    }
    if ($("#orderState").html() == '待发货'){
        $.ajax({
            type: "post",
            url: root.orderInter.integralOrderDelivery,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                logistics_company:$("#express_company").val(),
                logistics_num:$("#express_number").val(),
                order_id:orderId,
                member_id:JSON.parse(web.readCookie("loginData")).user.user_ID,
                login_account:JSON.parse(web.readCookie("loginData")).user.name
            }),
            //传入组装的参数
            success: function (data,user_data,succCallBack) {
                console.log(data)
                if(data.errorCode=="0") {
                    layer.msg('提交成功!', {icon: 6, time: 1000});
                    setTimeout( function () {
                        var index = parent.location.reload();
                        parent.layer.close(index);
                    },700);
                }else{
                    layer.msg(data.msg, {icon: 6, time: 1000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        })
    }else if ($("#orderState").html() == '待收货'){

        if ($("#orderSubmit").val()=='编   辑'){
            $("#orderSubmit").attr("value","提   交");
            $('#express_company').removeAttr("readonly");
            $('#express_number').removeAttr("readonly");
            return;
        }


        $.ajax({
            type: "post",
            url: root.orderInter.orderintegralSubmit,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                logistics_company:$("#express_company").val(),
                logistics_num:$("#express_number").val(),
                order_id:orderId,
                operate_userid:JSON.parse(web.readCookie("loginData")).user.user_ID,
                operate_username:JSON.parse(web.readCookie("loginData")).user.name
            }),
            //传入组装的参数
            success: function (data,user_data,succCallBack) {
                console.log(data)
                if(data.errorCode=="0") {
                    layer.msg('提交成功!', {icon: 6, time: 1000});
                    setTimeout( function () {
                        var index = parent.location.reload();
                        parent.layer.close(index);
                    },700);
                }else{
                    layer.msg(data.msg, {icon: 6, time: 1000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        })
    }

}
function renderOrderPage(data) {

    manjian=data
    /*商品总金额计算*/
    var goodsAmount = 0;



    for(var i = 0; i < data.listOrderItems.length; i++) {

        if(data.listOrderItems[i].activity_type==0){
            list.push(data.listOrderItems[i])
        }else if(data.listOrderItems[i].activity_type==10){
            list.push(data.listOrderItems[i])
        }else if(data.listOrderItems[i].activity_type==20){
            fullAmountMapValue+=data.listOrderItems[i].promotion_value
        }else if(data.listOrderItems[i].activity_type==30||data.listOrderItems[i].activity_type==31){
            fullQuantityValue+=data.listOrderItems[i].promotion_value
        }
        lvtotal += Number
        (Number(data.listOrderItems[i].sale_price-data.listOrderItems[i].init_sale_price)
            *Number(data.listOrderItems[i].buyyer_count)-Number(data.listOrderItems[i].coupon_value)
        )

        /*goodsAmount += Number(data.listOrderItems[i].init_sale_price) * Number(data.listOrderItems[i].buyyer_count);*/
        var vipjia= (data.listOrderItems[i].sale_price-data.listOrderItems[i].promotion_value/data.listOrderItems[i].buyyer_count).toFixed(2)
        goodsAmount += Number(vipjia) * Number(data.listOrderItems[i].buyyer_count);
    }

    data.listOrderItems=list

    if (list.length==0){
        $("#changePrice").attr("disabled","disabled");
        $("#zhe").attr("disabled","disabled");
        $("#gai").attr("disabled","disabled");
        // $("#freight").attr("disabled","disabled");
        $("#customServiceRemark").attr("disabled","disabled");
        // $("#abiaoqian").hide()
        $("#PriceChangeTrue").val("返回");

        // $.Huimodalalert("没有支持改价的商品",2000);
        // var index = parent.location.reload();
        // parent.layer.close(index);

    }

    for(var i = 0; i < data.listOrderItems.length; i++) {

        promotionValueTotal+=data.listOrderItems[i].promotion_value
        /*获取type*/
        var type=data.listOrderItems[i].sale_type
        if (type==20||type==30){
            lengthSister=lengthSister+1
        }
    }
    lvtotal=lvtotal-fullAmountMapValue-fullQuantityValue
    //没错,我这次想当个好人 bgm~
    length=Number(data.listOrderItems.length)
    /*根据类型隐藏批量改价*/
    if (lengthSister==length){
        $("#gai").attr("disabled","disabled");
        $("#zhe").attr("disabled","disabled");
    }
    if(typeId==2){
        if(list.length==0){
            if (lvtotal.toFixed(2)==0){
                $("#lv").html('+0.00');
            }else if (lvtotal.toFixed(2)>0){
                $("#lv").html("+"+lvtotal.toFixed(2));
            }else if (lvtotal.toFixed(2)<0){
                $("#lv").html(lvtotal.toFixed(2));
            }
        }else {
            $("#lv").html('+0.00');
        }

    }else {
        if (lvtotal.toFixed(2)==0){
            $("#lv").html('+0.00');
        }else if (lvtotal.toFixed(2)>0){
            $("#lv").html("+"+lvtotal.toFixed(2));
        }else if (lvtotal.toFixed(2)<0){
            $("#lv").html(lvtotal.toFixed(2));
        }
    }
    // 如果是用优惠券了，判断用券类型
    if(10 == data.orderBase.used_coupon){
        youvalue=data.orderCoupon.coupon_type

    }

    // $("#black").html(goodsAmount);
    /**
     * rowData.push(field.coupon_value);//13
     rowData.push(field.sku_id);
     rowData.push(field.buyyer_count);//15
     rowData.push(field.sale_price-field.init_sale_price);//16
     */

    $("#goodsAmount").html(goodsAmount.toFixed(2));
    $("#fare").html(data.orderBase.shipping_fee);
    $("#orderAmount").html((goodsAmount + data.orderBase.shipping_fee).toFixed(2));
    if(data.orderBase.order_status==80){
        $("#orderSubmit").css({
            display: "none"
        })
    }else {
        $("#orderSubmit").css({
            display: "inline"
        })
    }
    /*转换状态*/
    var order_status = changeOrderState(data.orderBase.order_status);
    if (data.orderBase.order_status == 50){
        $("#orderSubmit").attr("value","确   认");

    }else{
        $("#orderSubmit").attr("value","编   辑");
        $("#express_company").attr("readonly","true");
        $("#express_number").attr("readonly","true");
    }
    $("#orderState").html(order_status);

    $("#orderId").html(data.orderBase.order_id);
    $("#creatOrderTime").html(data.orderBase.created_at);
    if(data.orderBase.order_status == 10 || data.orderBase.order_status == 50) {
        $(".orderRemark").css({
            display: "none"
        })
    }
    //备注反显
    for(var i=0;i<data.listOrderRemark.length;i++){
        if(data.listOrderRemark[i].operate_type == 30){
            if(data.listOrderRemark[i].remark != null){
                $("#returnReason").html("全部拒收（"+data.listOrderRemark[i].remark+")")
            }else {
                $("#returnReason").html("全部拒收")
            }
            $("#closeOptioner").html(data.listOrderRemark[i].operate_username);
        }else if(data.listOrderRemark[i].operate_type == 40){
            $("#closeOptioner").html(data.listOrderRemark[i].operate_username);
            if(data.listOrderRemark[i].remark != null){
                $("#returnReason").html("全部退货（"+data.listOrderRemark[i].remark+")");
            }else {
                $("#returnReason").html("全部退货");
            }
            /*$("#closeTime").html(data.listOrderRemark[i].created_at);
            $("#closeOptioner").html(data.listOrderRemark[i].operate_username);
            $("#close-reason").html(changeCloseReason(data.listOrderRemark[i].refund_reason));
            $("#close-info").html(data.listOrderRemark[i].remark);*/
        }else if(data.listOrderRemark[i].operate_type == 70){
            var all = data.listOrderRemark[i].remark
            var index = all.lastIndexOf(";");
            var other = all.substring(0, index );
            $("#customServiceRemark").text(other);//客服备注
            var reason = all.substring(index + 1, all.length);
            $("select option[value='"+reason+"']").attr("selected","selected")
        }else if(data.listOrderRemark[i].operate_type == 60){
            $("#fareSeasonBox").show();
            $("#changeFareSeason").text(data.listOrderRemark[i].remark);//运费备注
        }
        if(data.listOrderRemark[i].operate_type == 20){
            if(data.listOrderRemark[i] == null) {
                $(".orderRemark textarea").val();
            } else {
                $(".orderRemark textarea").val(data.listOrderRemark[i].remark);
            }
        }
        if(data.listOrderRemark[i].operate_type == 10){
            if(data.listOrderRemark[i] == null) {
                $("#comfirmMoneyRemark").val();
            } else {
                $("#affirmMoney").css({
                    display:"none"
                })
                $("#comfirmMoneyRemark").html(data.listOrderRemark[i].remark);//确认认款备注
            }
        }
    }
    /*是否是异常订单*/
    if(data.orderAnomal == null){
        // $("#abnormalTypeBox").hide();
    }else {
        var abnormalType = "";
        var abnormalTypeArr = [];
        var rowArr = data.orderAnomal.anomal_type.split(',');
        function getAbnormalType(typeCode) {
            switch(typeCode) {
                case "10":
                    return "大额订单";
                    break;
                case "20":
                    return "临采商品订单";
                    break;
                case "30":
                    return "超赊欠额度订单";
                    break;
                case "40":
                    return "货到付款订单";
                    break;
                case  "50":
                    return "本机异常订单";
                    break;
                case  "60":
                    return "超卖订单";
                    break;
                case  "70":
                    return "低于成本价订单";
                    break;
            }
        }
        for(var i = 0; i < rowArr.length; i++) {
            abnormalTypeArr.push(getAbnormalType(rowArr[i]));
        }
        for(var j = 0; j < abnormalTypeArr.length; j++) {
            if(j < abnormalTypeArr.length - 1) {
                abnormalType += abnormalTypeArr[j] + ",";
            } else {
                abnormalType += abnormalTypeArr[j] + "";
            }
        }
        $("#abnormalType").html(abnormalType)
        // $("#abnormalTypeBox").show();

    }
    /*取消订单记录*/
    if(data.orderCancle != null) {
        $("#cancleTime").html(data.orderCancle.created_at);
        $("#optioner").html(data.orderCancle.cancle_name);
        $("#cancle-reason").html(changeCancleReason(data.orderCancle.cancle_reason));
        $("#cancle-info").html(data.orderCancle.cancel_remark);
    }
    /*关闭订单记录*/
    if(data.orderRefund != null) {
        $("#closeTime").html(data.orderRefund.created_at);
        // $("#closeOptioner").html(data.orderRefund.operate_username);
        $("#close-reason").html(changeCloseReason(data.orderRefund.refund_reason));
        $("#close-info").html(data.orderRefund.refund_desc);
    }
    /*基本信息*/
    $("#paid_integral").html((data.orderBase.used_total_points*100).toFixed(0));
    $("#buyer-name").html(data.orderBase.customer_name);
    // $("#created-order-code").html(data.orderBase.login_account);\
    $("#abnormalType").html(data.orderBase.login_account);
    $("#express_company").val(data.orderExt.express_company);
    $("#express_number").val(data.orderExt.express_num);
    $("#alisaAddress").html(data.orderExt.receiver_detail_address_alias);
    $("#receiver-address").html(data.orderExt.receiver_province_name + "" + data.orderExt.receiver_city_name + "" + data.orderExt.receiver_area_name + "" + data.orderExt.receiver_town_name + "" + data.orderExt.receiver_detail_address);
    $("#consignee").html(calculate(data.listAddressReceiver,1));
    $("#contact-way").html(data.orderExt.customer_phone);
    $("#cell-phone-number").html(calculate(data.listAddressReceiver,2));
    /*鼠标移出事件*/
    $("#consignee").mouseover(function () {
        $("#mouseBox").show();
        $("#mouseBox").html(calculate(data.listAddressReceiver, 1));
    }).mouseout(function () {
        $("#mouseBox").hide();
    })
    $("#cell-phone-number").mouseover(function () {
        $("#mouseBoxTwo").show();
        $("#mouseBoxTwo").html(calculate(data.listAddressReceiver, 3))
    }).mouseout(function () {
        $("#mouseBoxTwo").hide();
    })
    // $("#express_company").html(data.orderExt.express_company);
    // $("#express_number").html(data.orderExt.express_num);
    // express_company
    // express_num

    //授权收货人

    $("#sales-manager").html(data.orderExt.sales_manager_name);
    $("#contact-phone").html(data.orderExt.sales_manager_phone);
    $("#email").html(data.orderExt.customer_email);
    //固话
    $("#linePhone").html(data.orderExt.customer_landline_phone);
    if(data.orderBase.role_name == " "){
        $("#replaceBox").hide();
    }else {
        $("#replace-man").html(data.orderBase.role_name);
    }
    /*支付与配送方式*/
    $("#pay-type").html(changePayTypeState(data.orderBase.paid_type));
    $("#delivery-method").html(changeDeliveryMethodType(data.orderExt.sent_type));
    var couponconstant=(data.orderBase.shipping_fee).toFixed(2)
    if (data.orderCoupon!=null&&data.orderCoupon.coupon_type==20){
        // 运费券
        couponconstant=((data.orderBase.shipping_fee)-(data.orderCoupon.coupon_real_value)).toFixed(2)
        $("#freight").val(couponconstant);
        $("#yunfeiquanxinxi").html("运费优惠券:&nbsp;&nbsp;")

        if (fullAmountMapValue==0||fullQuantityValue==0){
            lvtotal='+0.00'
            $("#lv").html('+0.00');
        }else{
            lvtotal=lvtotal+data.orderCoupon.coupon_real_value
            $("#lv").html(lvtotal.toFixed(2));
        }


    }else if (data.orderCoupon!=null&&data.orderCoupon.coupon_type==10){
        $("#freight").val(couponconstant);
        $("#yunfeiquanxinxi").html("满减优惠券:&nbsp;&nbsp;")
    }else if(data.orderCoupon==null){
        $("#freight").val(couponconstant);
    }
    $("#predixt-delivery-time").html(data.orderExt.may_arrived_in);
    $("#appointment-time").html(data.orderExt.wanna_arrived_in);
    //实付金额
    $("#black").html(math((data.orderBase.final_total_amount).toFixed(2),couponconstant,(data.orderBase.paid_amount).toFixed(2),goodsAmount,promotionValueTotal));
    // $("#red").html((data.orderBase.paid_amount).toFixed(2));
    //结算金额
    $("#settlement-amount").html(data.orderBase.paid_amount);
    //付款方式
    if (data.orderBase.final_paid_type==null){
        $("#money-type").html("");
    }else {
        $("#money-type").html(changePayTypeState(JSON.parse(data.orderBase.final_paid_type)[0].code));
    }
    //结算方式
    if (data.orderBase.final_paid_type==null){
        $("#settlement-method").html("");
    }else {
        $("#settlement-method").html(changePayState(JSON.parse(data.orderBase.final_paid_type)[0].code));
    }
    //司机名称和电话
    /* if (data.orderExt.driver_name==null){
         $("#driver-phone").html("")
     }else {
         $("#driver-phone").html(data.orderExt.driver_name+data.orderExt.driver_phone);
     }*/
    //配送员名称和电话
    /*if (data.orderExt.deliver_name==null){
        $("#distributor-phone").html("")
    }else {
        $("#distributor-phone").html(data.orderExt.deliver_name+data.orderExt.deliver_phone);
    }*/

    /*发票信息*/
    /*$("#invoice-type").html(changeInvoiceType(data.orderInvoice.invoice_type));
    $("#invoice-title").html(data.orderInvoice.invoice_title);
    $("#invoice-content").html(data.orderInvoice.invoice_content);*/
    /*优惠券信息*/
    if(data.orderCoupon == null) {
        $("#couponInfo").html("无")
    } else {
        $("#couponInfo").html("满" + data.orderCoupon.use_condition + "元减" + data.orderCoupon.coupon_value + "元")
    }

    /*退款信息*/
    /*//对应后台最终退款总金额
    $("#returnMoney").html(data.orderBase.refund_amount_final);
    // 对应后台最终退款总金额
    $("#shouldReturn").html(data.orderBase.refund_amount_final);
    // 对应客户名称
    $("#conpany").html(data.orderBase.customer_name);
    // 对应退款单创建时间
    $("#return-askFor-time").html(data.orderBase.created_at);
    //对应订单关闭时间
    $("#return-finish-time").html(data.orderBase.close_time);
    // 退款备注
    $("#return-remark").html(data.orderBase.close_desc);*/
  /*  $("#returnTable").html("");
    for (var i=0;i<data.listOrderRefund.length;i++) {
        $("#returnTable").append('<tr><td class="col-2-1">退货单号：<span id="returnId"></span><a onclick="returnOrderInfo(\'退货单详情\',\'../afterSale/afterSaleService-returns.html\',\''+data.listOrderRefund[i].refund_id+'\',\''+data.listOrderRefund[i].order_id+'\')">'+data.listOrderRefund[i].refund_id+'</a></td><td class="col-2-1">申请时间：<span id="applytime"></span><span>'+data.listOrderRefund[i].created_at+'</span></td></tr>')
    }*/

    /*结算信息*/
    $("#goodsAmount").html((data.orderBase.final_total_amount - data.orderBase.shipping_fee).toFixed(2)); //商品金额
    $("#fare").html((data.orderBase.shipping_fee).toFixed(2)); //运费
    var aaa = 0;
    $("#littleFare").html(aaa.toFixed(2)); //运费减免
    if(data.orderCoupon == null) {
        $("#conMoney").html(aaa.toFixed(2)); //优惠券
    } else {
        $("#conMoney").html((data.orderCoupon.coupon_real_value).toFixed(2)); //优惠券
    }
    $("#orderAmount").html((data.orderBase.paid_amount).toFixed(2)); //订单金额
    /*商品信息*/
    dataSource.splice(0, dataSource.length); //清空数组

    $.each(data.listOrderItems, function(i, field) {
        // if(field.activity_type !=20){
        var rowData = new Array();
        rowData.push(field.product_pic);
        rowData.push(field.sku_code);
        rowData.push(field.product_name);
        rowData.push(field.buyyer_count);
        rowData.push(field.unit_name);
        rowData.push(field.init_sale_price);
        rowData.push(field.activity_type);
        rowData.push(field.promotion_value);

        dataSource.push(rowData);
        // }
    });

    initDataTable(dataSource);

    function initDataTable(dataSource) {
        if(data.listOrderItems==""){
            return false;
        }

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            data: dataSource,
            columnDefs: [{
                "visible": true,
            },
                {
                    "render": function (data, type, row, meta) {
                        var val ='<img title="" style="width: 100px;height: 100px;" name="" src="' + row[0] + '" alt="">'
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row) {
                        var val =  row[1]
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function(data, type, row) {
                        var val =  row[2]
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function(data, type, row) {
                        var val =  row[3]+row[4]
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function(data, type, row) {
                        var price = row[5]

                        var specialPrice = ""
                        if (row[6] == 10) {
                            specialPrice = row[7] / row[3]
                        }
                        price = (price - specialPrice).toFixed(2)

                        var val = '<span>'+(price*100).toFixed(0)+'积分/'+row[4]+'</span>'
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function(data, type, row) {
                        var price = row[5]

                        var specialPrice = ""
                        if (row[6] == 10) {
                            specialPrice = row[7] / row[3]
                        }
                        price = (price - specialPrice).toFixed(2)
                        var substotle = (price * row[3]).toFixed(2);
                        var val =  '<span>'+(substotle*100).toFixed(0)+'积分</span>'
                        return val;
                    },
                    "targets": 5
                },


            ]
        });
    };
    var handStr = '';
    //满减金额商品
    if(data.fullAmountReduceOrderItemsMap!="" && data.fullAmountReduceOrderItemsMap!=null){
        var arr=data.fullAmountReduceOrderItemsMap
        $.each(arr,function (index,i) {
            //算出该活动的所有商品小计和优惠值
            let countMoney = 0;
            let promotionMoney = 0;
            $.each(arr[index],function(k,v){
                promotionMoney = Number(promotionMoney)+Number(v.promotion_value);
                countMoney=Number(countMoney)+Number((v.sale_price * v.buyyer_count).toFixed(2));
            })

            let ruleStr = '<tr><td colspan="11"><div>' +
                '<span style="float: left;">'+arr[index][0].activity_rule+'</span>' +
                '<div style="float: right"><span style="float: left;">￥'+(countMoney).toFixed(2)+'</span><br>' +
                '<span style="float: left;">减：'+(promotionMoney).toFixed(2)+'</span></div>' +
                '</div></td></tr>';
            handStr +=ruleStr;
            $.each(arr[index],function(k,v){
                    console.log(arr[index])
                    var saletypes=""

                    if (v.sale_type==10){
                        saletypes = '指定展示价';
                    }
                    if (v.sale_type==20){
                        saletypes = '指定交易价';
                    }
                    if (v.sale_type==30){
                        saletypes = '指定展示价和指定交易价';
                    }
                    if (v.sale_type==40){
                        if(platform==10){
                            saletypes = '售价';
                        }else {
                            saletypes = '批发价';
                        }
                    }
                    if (v.sale_type==50){
                        saletypes = '分销价';
                    }
                if (v.sale_type==60){
                    saletypes = '售价';
                }
                    var ii=v.buyyer_count+v.unit_name
                    var xing=''
                    if (ii!=1){
                        xing='*'+ii
                    }

                    var valo=""



                    var value=v.coupon_value
                    if (youvalue==20){
                        value=0
                    }
                    var ll=v.sale_price-v.init_sale_price
                    // alert(v.sale_price)
                    // alert(v.init_sale_price)
                    var youhuiquan
                    //优惠券新算法
                    youhuiquan=Number(parseFloat(ll)*parseFloat(v.buyyer_count)-parseFloat(value))
                    var pp=v.init_sale_price*v.buyyer_count
                    if (pp==0){
                        var zhekou=0
                        youhuiquan='-'+(parseFloat(ll)*parseFloat(v.buyyer_count)-parseFloat(value))
                    }else{
                        var zhekou=((parseFloat(pp)+parseFloat(youhuiquan)).toFixed(2)/pp)*10
                    }
                if (typeId==1){
                    valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled"></span>';
                }else {
                    if(list.length==0){
                        valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled"></span>';

                    }else {
                        valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value="" id="danjia" disabled="disabled">';

                    }
                }

                /*单价类型*/
                var productType=v.sale_type
                if (productType==20||productType==30){
                    valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled">';
                }
                var vipjia= (v.sale_price-v.promotion_value/v.buyyer_count).toFixed(2)
                var xiaojis=(vipjia * v.buyyer_count).toFixed(2);
                if(typeId==1){
                    var substotle=(v.sale_price * v.buyyer_count).toFixed(2);
                }else {
                    if(list.length==0){
                        var substotle=(v.sale_price * v.buyyer_count).toFixed(2);

                    }else {
                        var substotle=""

                    }
                }
                    var data=""
                    if (v.sale_type==20||v.sale_type==30){
                        handStr+=
                            '<tr class="biaoge1">' +
                            '<td class="biaoge1-1" style="width: 270px;">'+v.sku_code+'</td>' +
                            '<td class="biaoge1-1" style="width: 112px;"><span id="handle_man">'+v.product_name+'</span></td>' +
                            '<td class="biaoge1-2" style="width: 101px;"><span class="count" >' +v.sku_info +xing+ '</span></td>' +
                            '<td class="biaoge1-3" style="width: 102px;"><span class="count">' + v.buyyer_count+v.unit_name + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 190px;"><span class="count">' +saletypes + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 127px;"><span class="oneprice">' + v.original_price + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 148px;"><span id="create_time">' +'¥'+ vipjia + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 240px;"><span id="create_time">' + v.coupon_value + '</span></td>'+
                            '<td class="w-150" style="width: 320px;"><span id="create_time">' +'¥'+ xiaojis  + '</span></td>'+
                            '<td class="w-200" style="width: 337px;"><span id="create_time">'+valo+'</span></td>'+
                            '<td class="w-200" style="width: 143px;"><span id="create_time"><span>'+substotle+'</span></span></td>'+
                            '</tr>';
                    }else {
                        handStr+=
                            '<tr class="biaoge1">' +
                            '<td class="biaoge1-1" style="width: 270px;">'+v.sku_code+'</td>' +
                            '<td class="biaoge1-1" style="width: 112px;"><span id="handle_man">'+v.product_name+'</span></td>' +
                            '<td class="biaoge1-2" style="width: 101px;"><span class="count" >' +v.sku_info +xing+ '</span></td>' +
                            '<td class="biaoge1-3" style="width: 102px;"><span class="count">' + v.buyyer_count+v.unit_name + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 190px;"><span class="count">' +saletypes + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 127px;"><span class="oneprice">' + v.original_price + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 148px;"><span id="create_time">' +'¥'+ vipjia + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 240px;"><span id="create_time">' + v.coupon_value + '</span></td>'+
                            '<td class="w-150" style="width: 320px;"><span id="create_time">' +'¥'+ xiaojis  + '</span></td>'+
                            '<td class="w-200" style="width: 337px;"><span id="create_time">'+valo+'</span></td>'+
                            '<td class="w-200" style="width: 143px;"><span id="create_time"><span>'+substotle+'</span></span></td>'+
                            '</tr>';
                    }
                }
            )
        })
    }
    $("#datatablemm").find("tbody").append($(handStr));

    var handStrnew = '';
    //满减金额商品
    if(data.fullQuantityReduceOrderItemsMap!="" && data.fullQuantityReduceOrderItemsMap!=null){
        var arr=data.fullQuantityReduceOrderItemsMap
        $.each(arr,function (index,i) {
            //算出该活动的所有商品小计和优惠值
            let countMoney = 0;
            let promotionMoney = 0;
            $.each(arr[index],function(k,v){
                promotionMoney = Number(promotionMoney)+Number(v.promotion_value);
                countMoney=Number(countMoney)+Number((v.sale_price * v.buyyer_count).toFixed(2));
            })

            let ruleStr = '<tr><td colspan="11"><div>' +
                '<span style="float: left;">'+arr[index][0].activity_rule+'</span>' +
                '<div style="float: right"><span style="float: left;">￥'+(countMoney).toFixed(2)+'</span><br>' +
                '<span style="float: left;">减：'+(promotionMoney).toFixed(2)+'</span></div>' +
                '</div></td></tr>';
            handStrnew +=ruleStr;
            $.each(arr[index],function(k,v){
                    console.log(arr[index])
                    var saletypes=""

                    if (v.sale_type==10){
                        saletypes = '指定展示价';
                    }
                    if (v.sale_type==20){
                        saletypes = '指定交易价';
                    }
                    if (v.sale_type==30){
                        saletypes = '指定展示价和指定交易价';
                    }
                    if (v.sale_type==40){
                        if(platform==10){
                            saletypes = '售价';
                        }else {
                            saletypes = '批发价';
                        }
                    }
                    if (v.sale_type==50){
                        saletypes = '分销价';
                    }
                if (v.sale_type==60){
                    saletypes = '售价';
                }
                    var ii=v.buyyer_count+v.unit_name
                    var xing=''
                    if (ii!=1){
                        xing='*'+ii
                    }

                    var valo=""



                    var value=v.coupon_value
                    if (youvalue==20){
                        value=0
                    }
                    var ll=v.sale_price-v.init_sale_price
                    // alert(v.sale_price)
                    // alert(v.init_sale_price)
                    var youhuiquan
                    //优惠券新算法
                    youhuiquan=Number(parseFloat(ll)*parseFloat(v.buyyer_count)-parseFloat(value))
                    var pp=v.init_sale_price*v.buyyer_count
                    if (pp==0){
                        var zhekou=0
                        youhuiquan='-'+(parseFloat(ll)*parseFloat(v.buyyer_count)-parseFloat(value))
                    }else{
                        var zhekou=((parseFloat(pp)+parseFloat(youhuiquan)).toFixed(2)/pp)*10
                    }
                    if (typeId==1){
                        valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled"></span>';
                    }else {
                        if(list.length==0){
                            valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled"></span>';

                        }else {
                            valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value="" id="danjia" disabled="disabled">';

                        }
                    }

                    /*单价类型*/
                    var productType=v.sale_type
                    if (productType==20||productType==30){
                        valo= '<input type="text" class="input-text radius w-60 mr-5 b" oninput="xiaoji(this)" value='+v.sale_price+' id="danjia" disabled="disabled">';
                    }
                var vipjia= (v.sale_price-v.promotion_value/v.buyyer_count).toFixed(2)
                var xiaojis=(vipjia * v.buyyer_count).toFixed(2);
                if(typeId==1){
                    var substotle=(v.sale_price * v.buyyer_count).toFixed(2);
                }else {
                    if(list.length==0){
                        var substotle=(v.sale_price * v.buyyer_count).toFixed(2);

                    }else {
                        var substotle=""

                    }
                }
                    var data=""
                    if (v.sale_type==20||v.sale_type==30){
                        handStrnew+=
                            '<tr class="biaoge1">' +
                            '<td class="biaoge1-1" style="width: 270px;">'+v.sku_code+'</td>' +
                            '<td class="biaoge1-1" style="width: 112px;"><span id="handle_man">'+v.product_name+'</span></td>' +
                            '<td class="biaoge1-2" style="width: 101px;"><span class="count" >' +v.sku_info +xing+ '</span></td>' +
                            '<td class="biaoge1-3" style="width: 102px;"><span class="count">' + v.buyyer_count+v.unit_name + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 190px;"><span class="count">' +saletypes + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 127px;"><span class="oneprice">' + v.original_price + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 148px;"><span id="create_time">' +'¥'+ vipjia + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 240px;"><span id="create_time">' + v.coupon_value + '</span></td>'+
                            '<td class="w-150" style="width: 320px;"><span id="create_time">' +'¥'+ xiaojis  + '</span></td>'+
                            '<td class="w-200" style="width: 337px;"><span id="create_time">'+valo+'</span></td>'+
                            '<td class="w-200" style="width: 143px;"><span id="create_time"><span>'+substotle+'</span></span></td>'+
                            '</tr>';
                    }else {
                        handStrnew+=
                            '<tr class="biaoge1">' +
                            '<td class="biaoge1-1" style="width: 270px;">'+v.sku_code+'</td>' +
                            '<td class="biaoge1-1" style="width: 112px;"><span id="handle_man">'+v.product_name+'</span></td>' +
                            '<td class="biaoge1-2" style="width: 101px;"><span class="count" >' +v.sku_info +xing+ '</span></td>' +
                            '<td class="biaoge1-3" style="width: 102px;"><span class="count">' + v.buyyer_count+v.unit_name + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 190px;"><span class="count">' +saletypes + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 127px;"><span class="oneprice">' + v.original_price + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 148px;"><span id="create_time">' +'¥'+ vipjia + '</span></td>'+
                            '<td class="biaoge1-3" style="width: 240px;"><span id="create_time">' + v.coupon_value + '</span></td>'+
                            '<td class="w-150" style="width: 320px;"><span id="create_time">' +'¥'+ xiaojis  + '</span></td>'+
                            '<td class="w-200" style="width: 337px;"><span id="create_time">'+valo+'</span></td>'+
                            '<td class="w-200" style="width: 143px;"><span id="create_time"><span>'+substotle+'</span></span></td>'+
                            '</tr>';
                    }
                }
            )
        })
    }
    $("#datatableshul").find("tbody").append($(handStrnew));
}

function juhe(el,row,count) {
    var ji=row*count
    var youhuiquan = $(el).val();
    var zhekou=(((youhuiquan/ji)+1)*10)
    //计算出新得金额
    var liu=((((zhekou/10)*parseFloat(row).toFixed(2)-parseFloat(row)).toFixed(2))*count).toFixed(2)
    //获取旧得金额
    $(el).parents('tr').find('.a').val(liu);
}
function dynamictwo(el,row,count) {
    var youhuiquan = $(el).val();
    //给两个位置赋值
    var white=$("#white").html();
    var black=$("#black").html();
    var red=$("#red").html();
    var lv=$("#lv").html();
    if (lv==''){
        lv=0
    }
    //获取所有的值
    var total=0
    $('.shun tr').each (function (i,dom) {
        var dom =$(dom).find('.a').val()
        if (dom==''||dom=='-'){
            dom=0
        }
        total+=parseFloat(dom)
    })
    total=Number(total)
        // +Number(lvtotal)
    if (total>=0.00){
        $('#lv').html('+'+total.toFixed(2))
    }else{
        $('#lv').html(total.toFixed(2))
    }


    red=(parseFloat(white)+parseFloat(black)+parseFloat(total)).toFixed(2)
    $('#red').html(red)
    //折扣率=折扣金额/小计+1
    var ji=row*count
    //计算折扣
    var zhekou=(((youhuiquan/ji)+1)*10)

    if (youhuiquan==''){
        zhekou=''
    }
    //赋值折扣
    $(el).parents('tr').find('.b').val(zhekou.toFixed(2));
}
function dynamic(el,row,count,type) {
    //获取折扣
    var zhekou = $(el).val();
    //计算差额
    var liu=((((zhekou/10)*parseFloat(row).toFixed(2)-parseFloat(row)).toFixed(2))*count).toFixed(2)

    if (zhekou==''){
        liu=''
    }
    //给金额赋值
    if (type!=1){
        $(el).parents('tr').find('.a').val(liu);
    }else{
        $(el).parents('tr').find('.a').val(zhekou);
    }

    if (type!=1){
        dynamictwo(liu,row,count,type)
    }
}
$('#changePrice').click(function (event) {
    event.preventDefault()
    //先判断有没有checked
    var zhe=$("#zhe").val()
    var gai=$("#gai").val()
    var subtotal=0
    var lvse=0
    $('.shun tr').each (function (i,dom) {
        var price=$(dom).find('.price').text().substring(1);
        var table = $('#datatable').DataTable();
        var oneprice=table.data()[i].toString().split(",")[6];
        var count=table.data()[i].toString().split(",")[16];
        if ($(this).find('.mt-10-ab').is(":checked")) {
            var priceTotal=0
            if (zhe!=''){
                $(dom).find('.b').val(zhe)
                if (zhe==''){
                    var liu=''
                }
                var liu=((((zhe/10)*parseFloat(oneprice).toFixed(2)-parseFloat(oneprice)).toFixed(2))*count).toFixed(2)
                $(dom).find('.a').val(liu)
                subtotal=parseFloat(parseFloat(subtotal)+parseFloat(liu)).toFixed(2)
                if (zhe>=10){
                    subtotal='+'+subtotal
                }
            }
            if (gai!=''){
                //先获取选中的小计的集合，然后用数量获取折扣，将折扣赋值给该输入框
                priceTotal+=parseFloat(price).toFixed(2)
                //用数量获取折扣
                var zhekou=(gai/parseFloat(priceTotal))*10
            }

        }
        lvse+=parseFloat($(dom).find('.a').val())
    })
    if (subtotal==0){
        return false
    }
    if (subtotal.substring(0,1)=='+'){
        $("#gai").val(subtotal.substring(1));
    }else{
        $("#gai").val(subtotal);
    }
    lvse=lvse-Number(fullAmountMapValue)-Number(fullQuantityValue)
    if (lvse>0){
        $("#lv").html('+'+lvse.toFixed(2));
    }else{
        $("#lv").html(lvse.toFixed(2));
    }
    var white=$("#white").html();
    var black=$("#black").html();
    $("#red").html(parseFloat(parseFloat(black)+parseFloat(white)+parseFloat(lvse)).toFixed(2));
});
//计算新小计
var rejectSomeArray = {};
function xiaoji(el) {
    var newxiaojijines=0//新小计
    var oldxiaojijines=0//旧小计
    //input输入框只能输入数字和 小数点后两位
    el.value = el.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    el.value = el.value.replace(/^\./g,""); //验证第一个字符是数字
    el.value = el.value.replace(/\.{2,}/g,""); //只保留第一个, 清除多余的
    el.value = el.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    el.value = el.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数

    //计算新小计
    var danjia=$(el).val()//获取新单价
    if(danjia=="0"){
        $.Huimodalalert('新单价不能为0',2000);
        return false;
    }
    var shuliang=el.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.children[1].innerHTML//获取数量
    var xiaojis=(danjia*shuliang).toFixed(2)//计算新小计
    el.parentElement.nextSibling.innerHTML=xiaojis//新小计赋值

    //计算折扣
   var newxiaojie=el.parentElement.nextSibling.innerHTML//获取新小计
    var oldxiaoji=el.parentElement.previousElementSibling.children[0].innerHTML
    oldxiaoji=oldxiaoji.replace("¥","");//获取旧小计
    var skucode=el.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML//获取skucode
    var xinxiaoji=""
    rejectSomeArray[skucode] ={
        "newxiaojijine":newxiaojie,
        "oldxiaojijine":oldxiaoji
    }
    for(var key in rejectSomeArray){
        console.log(rejectSomeArray[key])
        if(rejectSomeArray[key].newxiaojijine!="0.00"){
            newxiaojijines+=Number(rejectSomeArray[key].newxiaojijine)
            oldxiaojijines+=Number(rejectSomeArray[key].oldxiaojijine)
        }

    }
    var zheou=newxiaojijines-oldxiaojijines
    console.log(newxiaojijines+"新小计")
    console.log(oldxiaojijines+"旧小计")

//计算调整的金额
    if(zheou>0 ||zheou==0.00){
        $("#lv").html('+'+(zheou).toFixed(2));
    }else {
        $("#lv").html((zheou).toFixed(2));
    }

    var black=$("#black").html()
    var white=$("#white").html()
    var lv=$("#lv").html()
    /*console.log(parseFloat(black)+'商品总额')
    console.log(parseFloat(white)+'运费')
    console.log(parseFloat(lv)+'折扣')*/
    var red=(parseFloat(black)+parseFloat(white)+parseFloat(lv)).toFixed(2)
    $("#red").html(red)
}

//input输入框只能输入数字和 小数点后两位
function inputnum(obj,val){
    obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g,""); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
}


function tiaozheng(){
    if($("#jine").val()==""){
        $.Huimodalalert('请选择调整的类型！',2000);
        return false;
    }
    if($("#zhe").val()==""||$("#zhe").val()=="0"){
        $.Huimodalalert('请输入调整的金额！',2000);
        return false;
    }
    if($("#jine").val()==20){
        if(Number($("#zhe").val())>=Number($("#black").html())){
            $.Huimodalalert('优惠金额，不能大于或等于商品总额！',2000);
            $("#zhe").val("")
            return false;
        }
    }

    var xiaojis=0
    var zongge=0
    $('.shun tr').each (function (i,dom) {
        if($(dom).find('#prices').text()!=10) {
            var price = $(dom).find('.price').text().substring(1)//小计
            var skucode = $(dom).find('#skucode').text()//skucode
            xiaojis += Number(price)//总小计

            zongge+=1//累计计算有多少数据
        }
    })
    xiaojis=(xiaojis).toFixed(2)
    var zhe=$("#zhe").val()
    if(Number(zhe)>=xiaojis){
        $.Huimodalalert("不能大于或等于可修改的金额", 2000);
        return false
    }
    var yijing=0
    var dangqian=1
        $('.shun tr').each (function (i,dom) {
            if($(dom).find('#prices').text()!=10) {
                var Share =0
                var price = $(dom).find('.price').text().substring(1)//小计
                var count = $(dom).find('#shu').text().substring(0)//数量
                var vip = $(dom).find('#vip').text()//数量
                vip = vip.replace("¥", "");//截取数量
                count = count.replace("个", "");//截取数量
                count = count.replace("把", "");//截取数量
                var skucode = $(dom).find('#skucode').text()//skucode
                if(dangqian!= zongge){
                    Share = (price / xiaojis * $("#zhe").val()).toFixed(6)//小计分摊
                }else {
                    Share= $("#zhe").val()-yijing//最后一行小计分摊
                }

                var danShare = (Share / count).toFixed(2)//单个分摊

                if ($("#jine").val() == 10) {//调整增加时
                    var danjaix = (Number(vip) + Number(danShare)).toFixed(2)
                    $(dom).find('#danjia').val(danjaix)//新单价
                    xiaoji($(dom).find('#danjia')[0])
                } else {
                    var danjaix = (Number(vip) - Number(danShare)).toFixed(2)
                    if(dangqian!= zongge){
                        if(danjaix<0){
                            $.Huimodalalert("不能大于或等于可修改的金额", 2000);
                            return false
                        }else{
                            $(dom).find('#danjia').val(danjaix)//新单价
                        }
                    }else {
                        if(danjaix<=0){
                            $.Huimodalalert("不能大于或等于可修改的金额,不能为0", 2000);
                            return false
                        }else{
                            $(dom).find('#danjia').val(danjaix)//新单价
                        }
                    }


                    xiaoji($(dom).find('#danjia')[0])
                }
                yijing=(Number(yijing)+Number(danShare)*Number(count)).toFixed(2)
                dangqian+=1
            }

    })


}



//按钮隐藏
$("#changePrice").hide()
function valueCheck(dom,type) {
    //计算每个值，将不同的值计算出来
    var white=$("#white").html();
    var black=$("#black").html();
    var red=$("#red").html();
    var lv=$(dom).val();
    // var oldlv=$("#lv").html();
    //按钮显示
    $("#changePrice").show()
    if (type==1){
        if (lv!=''){
            $("#gai").attr("disabled","disabled");
            if (parseFloat(lv)>=10){
                var gai=((parseFloat(lv/10)*parseFloat(black))-parseFloat(black)).toFixed(2)
                $("#gai").val(gai)
                $('.shun tr').each (function (i,dom) {
                    if ($(this).find('.mt-10-ab').is(":checked")) {
                        $("#lv").html('+'+gai);
                    }
                })
            }else{
                var gai=((parseFloat(lv)*parseFloat(black)/10)-parseFloat(black)).toFixed(2)
                $("#gai").val(gai)
                $('.shun tr').each (function (i,dom) {if ($(this).find('.mt-10-ab').is(":checked")) {
                    $("#lv").html(gai);
                }})
            }
        }else{
            $("#changePrice").hide()
            $("#gai").removeAttr('disabled')
            $("#gai").val('')
            $('.shun tr').each (function (i,dom) {if ($(this).find('.mt-10-ab').is(":checked")) {
                $("#lv").html('-0.00')
            }})
        }
        if (gai==''||gai=='-'){
            gai=0
        }

        $('.shun tr').each (function (i,dom) {if ($(this).find('.mt-10-ab').is(":checked")) {
            red=(parseFloat(white)+parseFloat(black)+parseFloat($("#lv").html())).toFixed(2)
            $("#red").html(red)
        }})

    }else if (type==2){
        if (lv!=''){
            $("#zhe").attr("disabled","disabled");
            var totalZhe=0
            var num=0
            var zhekou=0
            $('.shun tr').each (function (i,dom) {
                if ($(this).find('.mt-10-ab').is(":checked")) {
                    totalZhe+=Number($(dom).find('.price').text().substring(1));
                    num=1;
                }
            })

            if (num>0){
                zhekou=((lv/parseFloat(totalZhe))+1)*10
            }else{
                zhekou=(((parseFloat(black)+parseFloat(lv)).toFixed(2)/parseFloat(black))*10).toFixed(2)
}
            // var zhe=(((parseFloat(black)+parseFloat(lv)).toFixed(2)/parseFloat(black))*10).toFixed(2)
            // // 添加隐形折扣
            // $(el).parents('tr').find('.b').attr('data-align',(((parseFloat(black)+parseFloat(lv)).toFixed(2)/parseFloat(black))*10))
            $("#zhe").val(Number(zhekou).toFixed(2))

            lv=Number(lv)
                // +Number(lvtotal)
            if (lv>0){
                $("#lv").html('+'+lv.toFixed(2))
            }else{
                $("#lv").html(lv.toFixed(2))
            }

        }else{
            $("#zhe").val('')
            $('.shun tr').each (function (i,dom) {if ($(this).find('.mt-10-ab').is(":checked")) {
                $("#lv").html('-0.00')
            }})
            $("#changePrice").hide()
            $("#zhe").removeAttr('disabled');
        }
        if (lv==''||lv=='-'){
            lv=0
        }
        red=(parseFloat(white)+parseFloat(black)+parseFloat(lv)).toFixed(2)
        $('.shun tr').each (function (i,dom) {if ($(this).find('.mt-10-ab').is(":checked")) {
            $("#red").html(red)
        }})
    }
}
function math(total,yunfei,paid_amount,goodsAmount,promotionValueTotal) {
    // total-yunfei  商品总金额
    // yunfei  运费金额
    // paid_amount 实付金额
    $("#white").html('+'+yunfei);
    /*var god=parseFloat(goodsAmount-promotionValueTotal).toFixed(2)*/
    var god=parseFloat(goodsAmount).toFixed(2)
    //不是优惠券
    //计算出总额，然后去赋值到优惠的金额上
    if(typeId==2){
        if(list.length==0){
            if (manjian.orderCoupon!=null&&manjian.orderCoupon.coupon_type==10){
                var total1=manjian.orderCoupon.coupon_real_value
                console.log(total1)
                $('#lv').html('-'+manjian.orderCoupon.coupon_real_value.toFixed(2))
                var  reds=(parseFloat(god)+parseFloat(yunfei)-parseFloat(total1)).toFixed(2)
                $('#red').html(reds)
            }else {
                $("#red").html((parseFloat(god)+parseFloat(yunfei)+parseFloat(lvtotal)).toFixed(2));
            }


        }else {
            if (manjian.orderCoupon!=null&&manjian.orderCoupon.coupon_type==10){
                var total1=manjian.orderCoupon.coupon_real_value
                console.log(total1)
                $('#lv').html('-'+manjian.orderCoupon.coupon_real_value.toFixed(2))
                var  reds=(parseFloat(god)+parseFloat(yunfei)-parseFloat(total1)).toFixed(2)
                $('#red').html(reds)
            }else {
                $("#red").html((parseFloat(god)+parseFloat(yunfei)+parseFloat(0.00)).toFixed(2));

            }

        }
    }else {
        if (manjian.orderCoupon!=null&&manjian.orderCoupon.coupon_type==10){
            var total1=manjian.orderCoupon.coupon_real_value
            console.log(total1)
            $('#lv').html('-'+manjian.orderCoupon.coupon_real_value.toFixed(2))
            var  reds=(parseFloat(god)+parseFloat(yunfei)-parseFloat(total1)).toFixed(2)
            $('#red').html(reds)
        }else {
            $("#red").html((parseFloat(god)+parseFloat(yunfei)+parseFloat(lvtotal)).toFixed(2));

        }
    }
    return god
}
function changeinput() {
    $("#freight").val("0.00");
    var old=$("#red").html();
    var lvOld=$("#white").html();
    $("#white").html("+0.00");
    $("#red").html((parseFloat(old)-parseFloat(lvOld)).toFixed(2));
}
function changeyunfei() {
    var lv=$("#lv").html();
    var jine=$("#black").html();
    var yunfei=$("#freight").val();
    if (yunfei==''){
        yunfei="0.00"
    }
    $("#white").html('+'+yunfei);
    $("#red").html((parseFloat(jine)+parseFloat(yunfei)+parseFloat(lv)).toFixed(2));
}
var jumpText
var ststus
/*请求改价*/
$('#PriceChangeTrue').click(function (event) {
    event.preventDefault();
    if (typeId==1||list.length==0){
        var index = parent.location.reload();
        parent.layer.close(index);
    }


    if ($('#gaijiayuanyin option:selected').val()==''){
        $.Huimodalalert("请先选择改价原因",2000);
        return false;
    }

    var reason = $('#gaijiayuanyin option:selected').val()


    layer.confirm('确认要改价吗？',function(index){
        //此处请求后台程序，下方是成功后的前台处理……
        var yunfei=$("#white").html();
        if (yunfei.substring(0,1)=='+'){
            yunfei=yunfei.replace("+","");
        }
        var loginData=JSON.parse(web.readCookie("loginData"));
        var userid = loginData.user.user_ID;
        var username = loginData.user.username;
        var remark=$('#customServiceRemark').val();
        /* 添加改价原因 */
        remark = remark +';'+reason
        var info=[]
        var table = $('#datatable').DataTable();
        $('.shun tr').each (function (i,dom) {
            var youhuiquan
            youhuiquan=$(dom).find('#danjia').val()
            if (youhuiquan!=undefined&&youhuiquan!=""){

            var product={
                skuId:table.data()[i].toString().split(",")[15],
                newPrice:youhuiquan,
            }
            info.push(product)
            }
        })
        $.ajax({
            type: "post",
            url: root.orderInter.order_price_change,
            cache: false,  //禁用缓存
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                orderId:orderId,//订单id
                shippingFee:yunfei,//运费
                operateUserid:userid,//操作人ID
                operateUsername:username,//操作人姓名
                remark:remark,//订单改价备注
                checkPrice:10,//是否忽略价格范围校验：10-不忽略；20-忽略
                changeList:info,//改价商品列表
            }),
            //传入组装的参数
            success: function (data,user_data,succCallBack) {
                console.log(data)
                var msg = ''
                var table = $('#datatable').DataTable();
                if(data.errorCode=="0") {
                    layer.msg('操作成功!', {icon: 6, time: 1000});
                    setTimeout( function () {
                        var index = parent.location.reload();
                        parent.layer.close(index);
                    },700);
                }else if (data.data==null&&data.errorCode=="1"){
                    layer.msg(data.msg, {icon: 6, time: 1000});
                    setTimeout( function () {
                        var index = parent.location.reload();
                        parent.layer.close(index);
                    },700);
                }else if (data.data!=null&&data.errorCode=="1"){
                    if (data.data.costOneTip!=''||data.data.costTwoTip!=''){
                        /* 判断三种情况 */
                        var one=data.data.costOneTip
                        var Two=data.data.costTwoTip
                        if (one!=''&&Two==''){
                            jumpText='存在低于成本价的商品（SkuCode: '+one+'），确认修改请输入密码'
                        }
                        if (one==''&&Two!=''){
                            jumpText='存在低于成本价80%的商品（SkuCode: '+Two+'），确认修改请输入密码'
                        }
                        if (one!=''&&Two!=''){
                            jumpText='存在低于成本价的商品（SkuCode: '+one+'）'+' \n '+
                                '存在低于成本价80%的商品（SkuCode: '+Two+')'+' \n '+
                                '确认修改请输入密码'
                        }
                        jumpmima(JSON.stringify(data))
                    }else if (data.data.lowerList!=''||data.data.upperList!=''){
                        msg='改价范围超过上下限,您确定要改价吗'
                        layer.confirm(msg,function () {
                            var a=data.data.lowerList
                            var b=data.data.upperList
                            var list=a.concat(b)
                            $.each (list,function (i,s) {
                                $('.shun tr').each (function (j,dom) {
                                    if (s==table.data()[j].toString().split(",")[0]){
                                        $(dom).css("background","#f7acbc");
                                    }else {
                                        $(dom).find('.a').css("color","");
                                    }
                                })
                            })

                            $.ajax({
                                type: "post",
                                url: root.orderInter.order_price_change,
                                cache: false,  //禁用缓存
                                dataType: "json",
                                contentType: "application/json",
                                data: JSON.stringify({
                                    orderId:orderId,//订单id
                                    shippingFee:yunfei,//运费
                                    operateUserid:userid,//操作人ID
                                    operateUsername:username,//操作人姓名
                                    remark:remark,//订单改价备注
                                    checkPrice:20,//是否忽略价格范围校验：10-不忽略；20-忽略
                                    changeList:info,//改价商品列表
                                }),
                                //传入组装的参数
                                success: function (data,user_data,succCallBack) {
                                    console.log(data)
                                    if(data.errorCode=="0") {
                                        layer.msg('操作成功!', {icon: 6, time: 1000});
                                        setTimeout( function () {
                                            var index = parent.location.reload();
                                            parent.layer.close(index);
                                        },700);
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    alert(XMLHttpRequest);
                                }
                            })

                        })
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        })
    });
})
/* 弹出输入密码页面 */
function jumpmima(data){
    sessionStorage.setItem("text",jumpText);
    sessionStorage.setItem("data",data);
    layer.open({
        type: 2,
        area: [400+'px', 300 +'px'],
        fix: false, //不固定
        maxmin: true,
        shade:0.4,
        title: "提示",
        content: "orderJump.html"
    });
    ststus = sessionStorage.getItem("status");
}

function fangfa(JSONdata){
    var data = JSON.parse(JSONdata)
    var table = $('#datatable').DataTable();
    var a=data.data.lowerList;
    var b=data.data.upperList;

    var list=a.concat(b);

    $.each (list,function (i,s) {
        $('.shun tr').each (function (j,dom) {
            if (s==table.data()[j].toString().split(",")[0]){
                $(dom).css("background","#f7acbc");
                // $(td).parent().css("background","red");
                // $(dom).find('.odd').css("color","red");
            }
        })
    })
    //将两种情况和起来，把得到的sku的值装进集合
    // layer.confirm(msg,function () {
    // $.each (list,function (i,s) {
    //     $('.shun tr').each (function (j,dom) {
    //         if (s==table.data()[j].toString().split(",")[15]){
    //             $(dom).find('.a').css("color","");
    //         }
    //     })
    // })

    var yunfei=$("#white").html();
    if (yunfei.substring(0,1)=='+'){
        yunfei=yunfei.replace("+","");
    }
    var loginData=JSON.parse(web.readCookie("loginData"));
    var userid = loginData.user.user_ID;
    var username = loginData.user.username;
    var reason = $('#gaijiayuanyin option:selected').val()
    var remark=$('#customServiceRemark').val();
    remark = remark +';'+reason
    var info=[]

    $('.shun tr').each (function (i,dom) {
        var youhuiquan
        youhuiquan=$(dom).find('#danjia').val()
        if (youhuiquan!=undefined && youhuiquan!=""){

            var product={
                skuId:table.data()[i].toString().split(",")[15],
                newPrice:youhuiquan,
            }
            info.push(product)
        }
    })
    if(a != '' || b != ''){
        layer.confirm('改价范围超过上下限,您确定要改价吗',function () {
            $.ajax({
                type: "post",
                url: root.orderInter.order_price_change,
                cache: false,  //禁用缓存
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    orderId:orderId,//订单id
                    shippingFee:yunfei,//运费
                    operateUserid:userid,//操作人ID
                    operateUsername:username,//操作人姓名
                    remark:remark,//订单改价备注
                    checkPrice:20,//是否忽略价格范围校验：10-不忽略；20-忽略
                    changeList:info,//改价商品列表
                }),
                //传入组装的参数
                success: function (data,user_data,succCallBack) {
                    console.log(data)
                    if(data.errorCode=="0") {
                        layer.msg('操作成功!', {icon: 6, time: 1000});
                        setTimeout( function () {
                            var index = parent.location.reload();
                            parent.layer.close(index);
                        },700);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest);
                }
            })
        })
    }else {
        $.ajax({
            type: "post",
            url: root.orderInter.order_price_change,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                orderId: orderId,//订单id
                shippingFee: yunfei,//运费
                operateUserid: userid,//操作人ID
                operateUsername: username,//操作人姓名
                remark: remark,//订单改价备注
                checkPrice: 20,//是否忽略价格范围校验：10-不忽略；20-忽略
                changeList: info,//改价商品列表
            }),
            //传入组装的参数
            success: function (data, user_data, succCallBack) {
                console.log(data)
                if (data.errorCode == "0") {
                    layer.msg('操作成功!', {icon: 6, time: 1000});
                    setTimeout(function () {
                        var index = parent.location.reload();
                        parent.layer.close(index);
                    }, 700);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        })
    }


    // var yunfei=$("#white").html();
    // if (yunfei.substring(0,1)=='+'){
    //     yunfei=yunfei.replace("+","");
    // }
    // var loginData=JSON.parse(web.readCookie("loginData"));
    // var userid = loginData.user.user_ID;
    // var username = loginData.user.username;
    // var remark=$('#customServiceRemark').val();
    // var info=[]
    //
    // $('.shun tr').each (function (i,dom) {
    //
    //     var youhuiquan
    //     youhuiquan=$(dom).find('#danjia').val()
    //     if (youhuiquan==''){
    //         return true;
    //     }
    //     var product={
    //         skuId:table.data()[i].toString().split(",")[15],
    //         newPrice:youhuiquan,
    //     }
    //     info.push(product)
    // })
    // $.ajax({
    //     type: "post",
    //     url: root.orderInter.order_price_change,
    //     cache: false,  //禁用缓存
    //     dataType: "json",
    //     contentType: "application/json",
    //     data: JSON.stringify({
    //         orderId:orderId,//订单id
    //         shippingFee:yunfei,//运费
    //         operateUserid:userid,//操作人ID
    //         operateUsername:username,//操作人姓名
    //         remark:remark,//订单改价备注
    //         checkPrice:20,//是否忽略价格范围校验：10-不忽略；20-忽略
    //         changeList:info,//改价商品列表
    //     }),
    //     //传入组装的参数
    //     success: function (data,user_data,succCallBack) {
    //         console.log(data)
    //         if(data.errorCode=="0") {
    //             layer.msg('操作成功!', {icon: 6, time: 1000});
    //             setTimeout( function () {
    //                 var index = parent.location.reload();
    //                 parent.layer.close(index);
    //             },700);
    //         }else{
    //             layer.confirm('改价范围超过上下限,您确定要改价吗',function () {
    //                 $.ajax({
    //                     type: "post",
    //                     url: root.orderInter.order_price_change,
    //                     cache: false,  //禁用缓存
    //                     dataType: "json",
    //                     contentType: "application/json",
    //                     data: JSON.stringify({
    //                         orderId:orderId,//订单id
    //                         shippingFee:yunfei,//运费
    //                         operateUserid:userid,//操作人ID
    //                         operateUsername:username,//操作人姓名
    //                         remark:remark,//订单改价备注
    //                         checkPrice:20,//是否忽略价格范围校验：10-不忽略；20-忽略
    //                         changeList:info,//改价商品列表
    //                     }),
    //                     //传入组装的参数
    //                     success: function (data,user_data,succCallBack) {
    //                         console.log(data)
    //                         if(data.errorCode=="0") {
    //                             layer.msg('操作成功!', {icon: 6, time: 1000});
    //                             setTimeout( function () {
    //                                 var index = parent.location.reload();
    //                                 parent.layer.close(index);
    //                             },700);
    //                         }
    //                     },
    //                     error: function (XMLHttpRequest, textStatus, errorThrown) {
    //                         alert(XMLHttpRequest);
    //                     }
    //                 })
    //             })
    //             var chengben=data.data.costList
    //             $.each (chengben,function (i,s) {
    //                 $('.shun tr').each (function (j,dom) {
    //                     if (s==table.data()[j].toString().split(",")[15]){
    //                         $(dom).css("background","#f7acbc");
    //                     }
    //                 })
    //             })
    //         }
    //     },
    //     error: function (XMLHttpRequest, textStatus, errorThrown) {
    //         alert(XMLHttpRequest);
    //     }
    // })
}
/*跳转退货订单详情*/
function returnOrderInfo(title,url,returnId,orderId){
    sessionStorage.setItem("returnId",returnId);
    sessionStorage.setItem("returnOrderId",orderId);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
/*订单备注编辑*/
var oldVal = "";

function toEdit() {
    oldVal = $(".orderRemark textarea").val();
    $("#isSaveFalse").css({
        display: "none"
    });
    $("#isSaveTrue").css({
        display: "block"
    });
    $(".orderRemark textarea").removeAttr("readonly");
}

function toCancle() {
    $(".orderRemark textarea").val(oldVal);
    $("#isSaveFalse").css({
        display: "block"
    });
    $("#isSaveTrue").css({
        display: "none"
    });
    $(".orderRemark textarea").css({
        border: "1px #ddd solid"
    });
    $(".errorMsg").css({
        display: "none"
    });
    $(".orderRemark textarea").attr("readonly", "readonly");
}

function remarkToSave() {
    if($(".orderRemark textarea").val().length > 500) {
        $(".orderRemark textarea").css({
            border: "1px red solid"
        });
        $(".errorMsg").css({
            display: "inline"
        });

    } else {
        $(".orderRemark textarea").css({
            border: "1px #ddd solid"
        });
        $(".errorMsg").css({
            display: "none"
        });
        var orderDetail = JSON.parse(sessionStorage.getItem("orderDetail"));
        var orderState = orderDetail.orderBase.order_status;

        function btnDisplay() {
            $("#isSaveFalse").css({
                display: "block"
            });
            $("#isSaveTrue").css({
                display: "none"
            });
            $(".orderRemark textarea").attr("readonly", "readonly");
        }
        /*进行添加备注请求*/
        btnDisplay();
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.orderInter.order_saveOrderRemark,
            cache: false, //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                bus_id: orderDetail.orderBase.order_id,
                operate_userid: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                operate_username: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                remark: $("#comfirmRemark").val(),
                "frist_remark_name":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

            }),
            success: function(result) {
                location.replace(location.href);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
}

/*详细信息编辑*/
function requireUpdataInter(updataData) {
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.orderInter.order_edit,
        cache: false, //禁用缓存
        dataType: "json",
        data: updataData,
        success: function(result) {
            if(result.code == 0) {
                $("#addressInpBox").css({
                    display: "none",
                });
                location.replace(location.href);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function updataDisplay(ids) {
    $(ids).css({
        display: "block",
    });
}

function updataSure(val) {
    var orderDetail = JSON.parse(sessionStorage.getItem("orderDetail"));
    switch(val) {
        /*修改那个标签*/
        case "#addressInp":
            /*收货地址*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                receiver_detail_address: $('#addressInp').val(),
            });
            requireUpdataInter(updataData);
            break;
        case "#consigneeInp":
            /*收货人*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                received_name: $('#consigneeInp').val(),
            });
            requireUpdataInter(updataData);
            break;

        case "#alisaAddressInp":
            /*地址别名*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                receiver_detail_address_alias: $('#alisaAddressInp').val(),
            });
            requireUpdataInter(updataData);
            break;
        case "#emailInp":
            /*邮箱*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                customer_email: $('#emailInp').val(),
            });
            requireUpdataInter(updataData);
            break;
        case "#phoneInp":
            /*手机号*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                received_phone: $('#phoneInp').val(),
            });
            requireUpdataInter(updataData);
            break;
        case "#linePhoneInp":
            /*固定电话*/
            var updataData = JSON.stringify({
                order_id: orderDetail.orderBase.order_id,
                customer_landline_phone: $('#linePhoneInp').val(),
            });
            requireUpdataInter(updataData);
            break;
    }
}

function updataCancel() {
    $("#addressInpBox").css({
        display: "none",
    });
    $("#consigneeInpBox").css({
        display: "none",
    });
    $("#alisaAddressInpBox").css({
        display: "none",
    });
    $("#emailInpBox").css({
        display: "none",
    });
    $("#phoneInpBox").css({
        display: "none",
    });
    $("#linePhoneInpBox").css({
        display: "none",
    });
}

function goToGoodsDetail(spuId) {
    sessionStorage.setItem("spuId", spuId);
    var index = layer.open({
        type: 2,
        title: "Code详情",
        content: "../../goods/goods-sku.html"
    });
    layer.full(index);
}



